/**
 * 
 */
package com.lanswon.service;

import java.sql.Date;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.lanswon.common.constants.Constants;
import com.lanswon.common.enums.MessageType;
import com.lanswon.common.enums.StaticMessage;
import com.lanswon.common.enums.UserStatus;
import com.lanswon.common.enums.UserType;
import com.lanswon.common.util.PropertiesUtils;
import com.lanswon.common.util.StringUtil;
import com.lanswon.common.util.TokenProccessor;
import com.lanswon.dao.UserAuthsMapper;
import com.lanswon.dao.UserMapper;
import com.lanswon.dao.VerificationMapper;
import com.lanswon.entity.UserAuthsVO;
import com.lanswon.entity.UserCard;
import com.lanswon.entity.UserVO;
import com.lanswon.qzsmk.service.commonservice.CardProductListVo;
import com.lanswon.qzsmk.service.commonservice.ResultObject;
import com.lanswon.qzsmk.service.commonservice.ResultVo;
import com.lanswon.qzsmk.service.commonservice.impl.DockingInternetService;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * @author lanswon
 *
 */
@Service
public class UserService {
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private UserAuthsMapper userAuthsMapper;
	@Autowired
	private CoreService appService;

	@Autowired
	private MobileService mobileService;

	@Autowired
	private VerificationMapper verificationMapper;

	@Autowired
	private UserService userService;

	@Autowired
	private UserCardService userCardService;
	
	@Autowired
	private DockingInternetService dockingInternetService;

	/*
	 * public Map<String, Object> addUser(String userName, String email, String
	 * phone) { Map<String, Object> dataMap = new HashMap(); try { // 插入数据
	 * UserVO userTagVO = new UserVO(); userTagVO.setUserName(userName);
	 * userTagVO.setEmail(email); userTagVO.setUserStatus("1");
	 * userTagVO.setMobile(phone); userTagVO.setCreateTime(new Date());
	 * userMapper.insert(userTagVO); // 返回useId dataMap.put("userId",
	 * userTagVO.getUserId()); dataMap.put("message", MessageType.MT007); }
	 * catch (Exception e) { dataMap.put("message", MessageType.MT008);
	 * e.printStackTrace(); } return dataMap;
	 * 
	 * }
	 */

	/**
	 * @param status
	 * @param string
	 * @return
	 */
	public String checkIsExist(String userName) {
		UserVO user = userMapper.getUserByName(userName);
		if (user == null) {
			return "insert";
		} else if (user.getUserId() != null && "2".equals(user.getUserStatus())) {
			return "update";
		} else if (user.getUserId() != null && "1".equals(user.getUserStatus())) {
			return "exist";
		} else {
			return "";
		}

	}

	public boolean addUserAuths(String userName, String password, String email, String phone, Long userId) {

		List<UserAuthsVO> authsTagVOs = new ArrayList<UserAuthsVO>();
		// 手机验证信息录入
		UserAuthsVO authsTagVO = new UserAuthsVO();
		authsTagVO.setIdentityType("phone");
		authsTagVO.setIdentifier(phone);
		authsTagVO.setCredential(password);
		authsTagVO.setUserId(userId);
		authsTagVOs.add(authsTagVO);

		// 邮件验证信息录入
		authsTagVO = new UserAuthsVO();
		authsTagVO.setIdentityType("email");
		authsTagVO.setIdentifier(email);
		authsTagVO.setCredential(password);
		authsTagVO.setUserId(userId);
		authsTagVOs.add(authsTagVO);

		// 用户名验证信息录入
		authsTagVO = new UserAuthsVO();
		authsTagVO.setIdentityType("common");
		authsTagVO.setIdentifier(userName);
		authsTagVO.setCredential(password);
		authsTagVO.setUserId(userId);
		authsTagVOs.add(authsTagVO);

		try {
			return userAuthsMapper.save(authsTagVOs);
		} catch (Exception e) {
			return false;
		}

	}

	/**
	 * zj
	 * 
	 * @param userName
	 * @return
	 */
	public UserVO queryUserByName(String userName) {
		return userMapper.getUserByName(userName);
	}

	/**
	 * zj
	 * 
	 * @param userName
	 * @return
	 */
	public Set<String> queryRolesByName(String userName) {
		return userAuthsMapper.queryRolesByName(userName);
	}

	/**
	 * @param map
	 * @return
	 */
	public boolean checkUser(Map<String, String[]> map) {
		boolean flag = false;
		String[] strs = map.get("user[]");
		if (strs != null && strs.length == 5) {
			for (String string : strs) {
				if (StringUtil.isEmpty(string)) {
					flag = false;
					break;
				}
				flag = true;
			}
		}
		return flag;
	}

	/**
	 * @param userId
	 * @return
	 */
	/*
	 * public boolean checkUpdate(Long userId) { UserVO user
	 * =userMapper.selectByPrimaryKey(userId);
	 * if("2".equals(user.getUserStatus())){ return true; }else { return false;
	 * } }
	 */

	/**
	 * @param userId
	 * @return
	 */
	public UserVO getUser(Long userId) {
		return userMapper.selectByPrimaryKey(userId);
	}

	/**
	 * 用户注册验证码
	 * 
	 * @param code
	 * @param usename
	 * @return
	 */
	public Map<String, Object> validateCode(HttpServletRequest request, String smsTemplate) {

		Map<String, Object> resultMap = new HashMap<String, Object>();
		String phone = request.getParameter("phone");
		// 传参校验
		if (StringUtil.isEmpty(phone)) {
			resultMap.put("code", 1);
			resultMap.put("message", MessageType.MT_SR_4);
			return resultMap;
		}
		// 手机号验证
		Map<String, Object> checkMap = checkPhone(phone);
		if ((int) checkMap.get("code") != 0) {
			resultMap.put("code", 1);
			resultMap.put("message", checkMap.get("message"));
			return resultMap;
		}
		Random random = new Random();
		String registerCode = "";
		for (int i = 0; i < 6; i++) {
			registerCode += random.nextInt(10);
		}
		Map<String, Object> registerCodeMap = new HashMap<String, Object>();
		registerCodeMap.put("code", registerCode);
		mobileService.sendSmsVerificationCode(phone, JSONObject.fromObject(registerCodeMap).toString(), smsTemplate);
		// 短信接口写入2
		resultMap.put("code", 0);
		resultMap.put("message", MessageType.MT007);
		resultMap.put("registerCode", registerCode);
		// 后台保存
		request.getSession().setAttribute("registerCode", registerCode);
		request.getSession().setAttribute("phone", phone);
		return resultMap;
	}

	/**
	 * @param username
	 * @return
	 */
	public Map<String, Object> checkUserName(String username) {

		Map<String, Object> resultMap = new HashMap<String, Object>();
		// 参数验证
		if (StringUtil.isEmpty(username)) {
			resultMap.put("code", 1);
			resultMap.put("message", MessageType.MT_SR_8);
			return resultMap;
		}
		// 用户验证
		if (userAuthsMapper.selectByType("common", username) == null) {
			resultMap.put("code", 0);
			resultMap.put("message", MessageType.MT007);
		} else {
			resultMap.put("code", 1);
			resultMap.put("message", MessageType.MT_ZJ_4);
		}
		// 格式验证
		if (username.matches(StaticMessage.phoneChecked)) {
			resultMap.put("code", 1);
			resultMap.put("message", MessageType.MT_MH_1);
		}
		// 格式验证
		if (username.matches(StaticMessage.emailChecked)) {
			resultMap.put("code", 1);
			resultMap.put("message", MessageType.MT_MH_2);
		}
		return resultMap;
	}

	/**
	 * @param email
	 * @return
	 */
	public Map<String, Object> checkEmail(String email) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		// 参数验证
		if (StringUtil.isEmpty(email)) {
			resultMap.put("code", 1);
			resultMap.put("message", MessageType.MT_SR_2);
			return resultMap;
		}
		// 邮箱验证
		if (userAuthsMapper.selectByType("email", email) == null) {
			resultMap.put("code", 0);
			resultMap.put("message", MessageType.MT007);
		} else {
			resultMap.put("code", 1);
			resultMap.put("message", MessageType.MT_ZJ_1);
		}
		// 格式验证
		if (!email.matches(StaticMessage.emailChecked)) {
			resultMap.put("code", 1);
			resultMap.put("message", MessageType.MT_GS_1);
		}
		return resultMap;
	}

	/**
	 * 发送验证码
	 * 
	 * @param phone
	 * @return
	 */
	public Map<String, Object> checkPhone(String phone) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		// 参数验证
		if (StringUtil.isEmpty(phone)) {
			resultMap.put("code", 1);
			resultMap.put("message", MessageType.MT_SR_4);
			return resultMap;
		}
		// 手机验证
		if (userAuthsMapper.selectByType("phone", phone) == null) {
			resultMap.put("code", 0);
			resultMap.put("message", MessageType.MT007);
		} else {
			resultMap.put("code", 1);
			resultMap.put("message", MessageType.MT_ZJ_2);
		}
		// 格式验证
		if (!phone.matches(StaticMessage.phoneChecked)) {
			resultMap.put("code", 1);
			resultMap.put("message", MessageType.MT_GS_2);
		}
		return resultMap;
	}

	/**
	 * @param page
	 * @param limit
	 * @param content
	 * @param type
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public Map<String, Object> load(Integer page, Integer limit, String type, String content) {

		if (page == null) {
			page = 1;
		}

		int pageindex = (page - 1) * limit;
		List<UserVO> userVOs = new ArrayList<>();
		int count;
		// !StringUtil.isEmpty(type) &&
		if (!StringUtil.isEmpty(content)) {
			userVOs = userMapper.loadByCondition(pageindex, limit, type, content);
			count = userMapper.countByCondition(type, content);

		} else {
			userVOs = userMapper.load(pageindex, limit);
			count = userMapper.count();
		}

		// 处理数据
		JSONArray jsonArray = new JSONArray();
		for (UserVO userVO : userVOs) {
			Map<String, Object> map = new HashMap<>();
			map.put("userId", userVO.getUserId());
			map.put("userName", userVO.getUserName());
			map.put("userStatusStr", UserStatus.getValueByCode(userVO.getUserStatus().intValue()));
			map.put("email", userVO.getEmail() == null ? "" : userVO.getEmail());
			map.put("phone", userVO.getMobile() == null ? "" : userVO.getMobile());
			map.put("userTypeStr", UserType.getValueByCode(userVO.getUserType().intValue()));
			map.put("realName", userVO.getRealName() == null ? "" : userVO.getRealName());
			JSONObject json = JSONObject.fromObject(map);
			jsonArray.add(json);
		}
		// 组装数据
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("code", 0);
		jsonObject.put("msg", "");
		jsonObject.put("count", count);
		jsonObject.put("data", jsonArray);
		return jsonObject;
	}

	/**
	 * @param userId
	 * @return
	 */
	public void forbidden(Long userId) {
		userMapper.forbidden(userId);
	}

	/**
	 * @param userId
	 */
	public void restart(Long userId) {
		userMapper.restart(userId);
	}

	/**
	 * @param userId
	 * @return
	 */
	public Map<String, Object> getUserMessage(Long userId) {
		UserVO userVO = userMapper.selectByPrimaryKey(userId);
		List<UserAuthsVO> userAuthsVOs = userAuthsMapper.selectByUserId(userId);
		Map<String, Object> dataMap = new HashMap<String, Object>();

		dataMap.put("地址", userVO.getAddress() == null ? "" : userVO.getAddress());
		dataMap.put("真实姓名", userVO.getRealName() == null ? "" : userVO.getRealName());
		for (UserAuthsVO userAuthsVO : userAuthsVOs) {
			String type = dealType(userAuthsVO.getIdentityType());
			dataMap.put(type, userAuthsVO.getIdentifier() == null ? "" : userAuthsVO.getIdentifier());
			dataMap.put("密码", userAuthsVO.getCredential() == null ? "" : userAuthsVO.getCredential());
		}

		return dataMap;
	}

	private String dealType(String identityType) {
		if ("common".equals(identityType)) {
			return "用户名";
		} else if ("phone".equals(identityType)) {
			return "手机号";
		} else {
			return "邮箱";
		}
	}

	/**
	 * @param request
	 * @return
	 */
	/*
	 * public Map<String, Object> doRegister(HttpServletRequest request) {
	 * Map<String, Object> resultMap = new HashMap<String, Object>(); String
	 * userName = request.getParameter("userName"); String password =
	 * request.getParameter("password"); String email =
	 * request.getParameter("email"); String verifyCode =
	 * request.getParameter("verifyCode"); // 后台获取 String registerCode =
	 * (String) request.getSession().getAttribute("registerCode"); String phone
	 * = (String) request.getSession().getAttribute("phone"); // 参数为空 if
	 * (StringUtil.isEmpty(userName) || StringUtil.isEmpty(password) ||
	 * StringUtil.isEmpty(email) || StringUtil.isEmpty(phone) ||
	 * StringUtil.isEmpty(verifyCode) || StringUtil.isEmpty(registerCode)) {
	 * resultMap.put("code", 1); resultMap.put("message", MessageType.MT001);
	 * return resultMap; } // 验证码校验 if (!verifyCode.equals(registerCode)) {
	 * resultMap.put("code", 1); resultMap.put("message", MessageType.MT_YZ_1);
	 * return resultMap; } // 验证数据库已有数据 if (checkRegisterParam(email, phone,
	 * userName)) { resultMap.put("code", 1); resultMap.put("message",
	 * MessageType.MT_ZJ_5); return resultMap; }
	 * 
	 * try { // 添加用户 Map<String, Object> userMap = addUser(userName, email,
	 * phone); Long userId = (Long) userMap.get("userId"); if (userId == null) {
	 * resultMap.put("code", 1); resultMap.put("message", MessageType.MT008);
	 * return resultMap; } password = StringUtil.md5(password);
	 * addUserAuths(userName, password, email, phone, userId); Map map = new
	 * HashMap<>(); StringUtil.putIntoMap(map, "userId", userId);
	 * StringUtil.putIntoMap(map, "userName", userName);
	 * StringUtil.putIntoMap(map, "email", email); StringUtil.putIntoMap(map,
	 * "phone", phone); resultMap.put("code", 0); resultMap.put("data", map);
	 * resultMap.put("message", MessageType.MT007); // 后台保存
	 * request.getSession().setAttribute("userId", userId); } catch (Exception
	 * e) { resultMap.put("code", 1); resultMap.put("message",
	 * MessageType.MT008); e.printStackTrace(); } return resultMap; }
	 */

	/**
	 * @param userName
	 * @param password
	 * @param realName
	 * @param email
	 * @param phone
	 * @return
	 */

	private boolean checkRegisterParam(String email, String phone, String userName) {
		if ((int) checkEmail(email).get("code") == 0 && (int) checkPhone(phone).get("code") == 0
				&& (int) checkUserName(userName).get("code") == 0) {
			return false;
		} else {
			return true;
		}
	}

	/**
	 * @param paperNo
	 * @param paperType
	 * @param request
	 * @return
	 * @throws Exception 
	 */
	@SuppressWarnings("unchecked")
	public Map<String, Object> bind(UserVO user, String[] cardNos) throws Exception {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		if (StringUtil.isEmpty(user.getCustomerNo())) {// 不存在则查询客户编号
			ResultVo resultVo = dockingInternetService.queryCardProdunctByPersonal(user.getPapertype(),user.getPaperno(), "");
			if (resultVo.getResultStatus().getCode() != 200) {
				throw new Exception(resultVo.getResultStatus().getMessage());
			}else{
				ResultObject ro = (ResultObject) resultVo.getServiceObject();
				List<Object> items = ro.getItems();//所有的
				if(items==null&&items.size()==0){
					resultMap.put("code", 6);
					resultMap.put("message", "该用户还未开通市民卡");//dataMap.get("message")
					return resultMap;
				}
			}
			// 查询客户编号
			Map<String, Object> dataMap = appService.queryPersonalByPaperNoAndPaperType(user.getPapertype(),
					user.getPaperno());
			if ((int) dataMap.get("code") != 0) {
				resultMap.put("code", 6);
				resultMap.put("message", "该用户还未开通市民卡");//dataMap.get("message")
				return resultMap;
			}
			JSONObject personal = ((JSONObject) dataMap.get("data"));
			user.setCustomerNo((String) personal.get("customerNo"));
			userMapper.updateByPrimaryKeySelective(user);
		} 
		for (int i = 0; i < cardNos.length; i++) {
			UserCard ucCard = userCardService.getUserCardByCardNo(cardNos[i]);
			if (ucCard != null) {
				resultMap.put("code", 7);
				resultMap.put("message", "该证件号已被绑定");
				return resultMap;
			}
			if(!verifyCardNo(cardNos[i])){
				resultMap.put("code", 8);
				resultMap.put("message", "证件号输入有误");
				return resultMap;
			}
			UserCard newuc = new UserCard();
			newuc.setCardNo(cardNos[i]);
			//newuc.setCardType(Byte.parseByte(cardType));
			newuc.setIdNo(user.getPaperno());
			userCardService.addUserCard(newuc);
			
		}
		resultMap.put("code", 0);
		resultMap.put("message", "绑定成功");
		return resultMap;
	}

	public  boolean verifyCardNo(String cardNo) throws Exception {
		try {
			if ((cardNo == null) || ("".equals(cardNo)) || (cardNo.length() != 12)) {
				return false;
			}

			int length = cardNo.length();

			int iLuhn = Integer.parseInt(cardNo.substring(4, 5));

			String luhnData = cardNo.substring(0, 4) + cardNo.substring(5, length);

			return (calcLuhn(luhnData) == iLuhn);
		} catch (Exception e) {
			throw e;
		}
	}
	public int calcLuhn(String data) {
		int length = data.length();

		int[] allData = new int[length];

		int sumOdd = 0;
		int sumEven = 0;

		for (int i = 0; i < length; ++i) {
			allData[i] = Integer.parseInt(data.substring(length - i - 1, length - i));

			if (i % 2 == 0) {
				sumOdd += allData[i];
			} else {
				allData[i] = ((allData[i] * 2 > 9) ? allData[i] * 2 - 9 : allData[i] * 2);

				sumEven += allData[i];
			}

		}

		int mod = (sumOdd + sumEven) % 10;

		int luhn = (mod == 0) ? 0 : 10 - mod;

		return luhn;
	}
	
	public Map<String, Object> demo(HttpServletRequest request) {
		String message = "";
		int code = 1;
		String paperType = request.getParameter("paperType");
		String paperNo = request.getParameter("paperNo");
		String userId = request.getParameter("userId");

		if (!StringUtil.isEmpty(paperType) && !StringUtil.isEmpty(paperNo) && !StringUtil.isEmpty(userId)) {
			UserVO vo = userMapper.selectByPrimaryKey(Long.valueOf(userId));
			if (vo.getPapertype() != null && vo.getPaperno() != null) {
				vo.setPapertype(paperType);
				vo.setPaperno(paperNo);
				userMapper.updateByPrimaryKeySelective(vo);
				code = 0;
				message = "绑定信息成功";
			} else {
				message = "该证件已绑定账号";
			}
		} else {
			message = "请输入绑定信息";
		}
		// 返回信息
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("code", code);
		resultMap.put("message", message);
		return resultMap;

	}

	/**
	 * @param dataMap
	 * @return
	 */
	public Map<String, Object> updateTokenById(Map<String, Object> dataMap) {
		// 登陆有误不处理
		if ((int) dataMap.get("code") != 0) {
			return dataMap;
		}
		String token = TokenProccessor.getInstance().makeToken();
		// 解析
		Map<String, Object> map = (Map<String, Object>) dataMap.get("data");
		// 更新数据库信息
		UserVO vo = userMapper.selectByPrimaryKey((Long) map.get("userId"));
		token = token + System.currentTimeMillis();
		vo.setToken(token);
		userMapper.updateByPrimaryKeySelective(vo);
		// 加入app端token信息
		map.put("token", token);
		dataMap.put("data", map);
		System.out.println(dataMap);
		return dataMap;
	}

	/**
	 * @return
	 */

	/**
	 * @param token
	 * @param userId
	 * @return
	 */
	public Map<String, String> checkToken(String token, Long userId) {
		// 加载
		PropertiesUtils.load("/config/system.properties");
		String str = PropertiesUtils.get("token");
		Map<String, String> dataMap = new HashMap();
		// 验证token
		if (!str.equals(token)) {
			dataMap.put("flag", "false");
			dataMap.put("message", MessageType.MT002);
			return dataMap;
		}
		// 验证userId
		UserVO vo = userMapper.selectByPrimaryKey(userId);
		if (vo == null) {
			dataMap.put("flag", "false");
			dataMap.put("message", MessageType.MT003);
			return dataMap;
		}

		String sqlToken = vo.getToken();
		if (System.currentTimeMillis()
				- Long.valueOf(sqlToken.substring(sqlToken.length() - 13, sqlToken.length())) > 1000 * 60 * 30) {
			dataMap.put("flag", "true");
			dataMap.put("message", MessageType.MT004);
			return dataMap;
		}

		// 更新token
		vo.setToken(token + System.currentTimeMillis());
		userMapper.updateByPrimaryKeySelective(vo);
		dataMap.put("flag", "true");
		return dataMap;
	}

	/**
	 * 发送验证码
	 * 
	 * @param request
	 * @return
	 */
	public Map<String, Object> sendPWValidate(HttpServletRequest request) {
		String phone = request.getParameter("phone");
		// 1、验证是否注册，2、不验证是否注册
		// String type = request.getParameter("type");
		Map<String, Object> dataMap = new HashMap<>();
		// 传参校验
		if (StringUtil.isEmpty(phone)) {
			dataMap.put("code", 1);
			dataMap.put("message", MessageType.MT_SR_4);
			return dataMap;
		}
		// 手机号是否存在
		Integer userId = userAuthsMapper.selectByType("phone", phone);
		if (userId == null) {
			dataMap.put("code", 1);
			dataMap.put("message", MessageType.MT_CX_3);
			return dataMap;
		}
		// 业务处理
		try {
			String passwordCode = "";
			Random random = new Random();
			for (int i = 0; i < 6; i++) {
				passwordCode += random.nextInt(10);
			}
			// 短息接口写入
			Map<String, Object> verifyCodeMap = new HashMap<>();
			verifyCodeMap.put("code", passwordCode);
			mobileService.sendSmsVerificationCode(phone, JSONObject.fromObject(verifyCodeMap).toString(),
					Constants.SMS_UPDATEP_ASSWORD);
			dataMap.put("code", 0);
			dataMap.put("message", MessageType.MT007);
			dataMap.put("passwordCode", passwordCode);

			request.getSession().setAttribute("passwordCode", passwordCode);
			request.getSession().setAttribute("changeUser", userId.toString());

		} catch (Exception e) {
			dataMap.put("code", 1);
			dataMap.put("message", MessageType.MT008);
			e.printStackTrace();
		}
		return dataMap;
	}

	/**
	 * 忘记密码
	 * 
	 * @param request
	 * @return
	 */
	/*
	 * public Map<String, Object> changeValidate(HttpServletRequest request) {
	 * String password = request.getParameter("password"); String verifyCode =
	 * request.getParameter("verifyCode");
	 * 
	 * String passwordCode = (String)
	 * request.getSession().getAttribute("passwordCode"); String userId =
	 * (String) request.getSession().getAttribute("changeUser");
	 * 
	 * Map<String, Object> dataMap = new HashMap<>(); // 传参校验 if
	 * (StringUtil.isEmpty(passwordCode) || StringUtil.isEmpty(userId)) {
	 * dataMap.put("code", 1); dataMap.put("message", MessageType.MT_SR_5);
	 * return dataMap; } if (StringUtil.isEmpty(password)) { dataMap.put("code",
	 * 1); dataMap.put("message", MessageType.MT_SR_3); return dataMap; } if
	 * (StringUtil.isEmpty(verifyCode)) { dataMap.put("code", 1);
	 * dataMap.put("message", MessageType.MT_SR_6); return dataMap; } // 验证码校验
	 * if (!verifyCode.equals(passwordCode)) { dataMap.put("code", 1);
	 * dataMap.put("message", MessageType.MT_YZ_1); return dataMap; } // 业务处理
	 * try { List<UserAuthsVO> userList =
	 * userAuthsMapper.selectByUserId(Long.valueOf(userId)); password =
	 * StringUtil.md5(password); if
	 * (password.equals(userList.get(0).getCredential())) { dataMap.put("code",
	 * 1); dataMap.put("message", MessageType.MT_MM_1); return dataMap; } for
	 * (UserAuthsVO userAuthsVO : userList) {
	 * userAuthsVO.setCredential(password);
	 * userAuthsMapper.updateByPrimaryKeySelective(userAuthsVO); }
	 * dataMap.put("code", 0); dataMap.put("message", MessageType.MT007); }
	 * catch (Exception e) { dataMap.put("code", 1); dataMap.put("message",
	 * MessageType.MT008); e.printStackTrace(); } return dataMap; }
	 */

	/**
	 * 修改密码
	 * 
	 * @param string
	 * @param request
	 * @return
	 */
	public Map<String, Object> changePassword(Long userId, String oldPassword, String newPassword) {
		Map<String, Object> dataMap = new HashMap<>();

		// 业务处理
		try {
			UserVO user = userMapper.selectByPrimaryKey(userId);
			if (!StringUtil.md5(oldPassword).equals(user.getPassword())) {
				dataMap.put("code", 1);
				dataMap.put("message", MessageType.MT_MM_2);
				return dataMap;
			}
			newPassword = StringUtil.md5(newPassword);
			user.setPassword(newPassword);
			userMapper.updateByPrimaryKeySelective(user);
		} catch (Exception e) {
			dataMap.put("code", 1);
			dataMap.put("message", MessageType.MT008);
			e.printStackTrace();
		}
		return dataMap;
	}

	/**
	 * @param userId
	 * @param request
	 * @return
	 */
	/*
	 * public Map<String, Object> changeEmail(Long userId, String oldEmail,
	 * String newEmail) { Map<String, Object> dataMap = new HashMap<>(); // 邮箱校验
	 * Map<String, Object> checkMap = checkEmail(newEmail); if ((int)
	 * checkMap.get("code") != 0) { dataMap.put("code", 1);
	 * dataMap.put("message", checkMap.get("message")); return dataMap; }
	 * UserAuthsVO userAuthsVO = userAuthsMapper.selectByUserIdAndType(userId,
	 * "email"); if (!oldEmail.equals(userAuthsVO.getIdentifier())) {
	 * dataMap.put("code", 1); dataMap.put("message", MessageType.MT_CX_2);
	 * return dataMap; } // 业务处理 try { UserVO userVO =
	 * userMapper.selectByPrimaryKey(userId); userVO.setEmail(newEmail);
	 * userMapper.updateByPrimaryKeySelective(userVO);
	 * userAuthsVO.setIdentifier(newEmail);
	 * userAuthsMapper.updateByPrimaryKeySelective(userAuthsVO);
	 * dataMap.put("code", 0); dataMap.put("message", MessageType.MT007); }
	 * catch (Exception e) { dataMap.put("code", 1); dataMap.put("message",
	 * MessageType.MT008); e.printStackTrace(); } return dataMap; }
	 */

	/**
	 * @param userId
	 * @param request
	 * @return
	 */
	public Map<String, Object> changePhone(Long userId, String oldPhone, String newPhone) {
		Map<String, Object> dataMap = new HashMap<>();
		// 手机校验
		Map<String, Object> checkMap = checkPhone(newPhone);
		if ((int) checkMap.get("code") != 0) {
			dataMap.put("code", 1);
			dataMap.put("message", checkMap.get("message"));
			return dataMap;
		}
		UserAuthsVO userAuthsVO = userAuthsMapper.selectByUserIdAndType(userId, "phone");
		if (!oldPhone.equals(userAuthsVO.getIdentifier())) {
			dataMap.put("code", 1);
			dataMap.put("message", MessageType.MT_CX_3);
			return dataMap;
		}
		// 业务处理
		try {
			UserVO userVO = userMapper.selectByPrimaryKey(userId);
			userVO.setMobile(newPhone);
			userMapper.updateByPrimaryKeySelective(userVO);
			userAuthsVO.setIdentifier(newPhone);
			userAuthsMapper.updateByPrimaryKeySelective(userAuthsVO);
			dataMap.put("code", 0);
			dataMap.put("message", MessageType.MT007);
		} catch (Exception e) {
			dataMap.put("code", 1);
			dataMap.put("message", MessageType.MT008);
			e.printStackTrace();
		}
		return dataMap;
	}

	/**
	 * @param request
	 * @param newPhone
	 * @return
	 */
	public Map<String, Object> sendPhoneValidate(HttpServletRequest request, String newPhone) {
		Map<String, Object> dataMap = new HashMap<>();
		// 手机号是否存在
		Integer userId = userAuthsMapper.selectByType("phone", newPhone);
		if (userId != null) {
			dataMap.put("code", 1);
			dataMap.put("message", MessageType.MT_ZJ_2);
			return dataMap;
		}
		// 业务处理
		try {
			String phoneCode = "";
			Random random = new Random();
			for (int i = 0; i < 6; i++) {
				phoneCode += random.nextInt(10);
			}
			// 短息接口写入
			Map<String, Object> verifyCodeMap = new HashMap<>();
			verifyCodeMap.put("code", phoneCode);
			mobileService.sendSmsVerificationCode(newPhone, JSONObject.fromObject(verifyCodeMap).toString(),
					Constants.SMS_UPDATEP_ASSWORD);
			dataMap.put("code", 0);
			dataMap.put("phoneCode", phoneCode);

			request.getSession().setAttribute("phoneCode", phoneCode);
			request.getSession().setAttribute("newPhone", newPhone);

		} catch (Exception e) {
			dataMap.put("code", 1);
			dataMap.put("message", MessageType.MT008);
			e.printStackTrace();
		}
		return dataMap;
	}

	/**
	 * @param verifyCode
	 * @param userId
	 * @param request
	 * @return
	 */
	public Map<String, Object> changePhoneValidate(String verifyCode, Long userId, HttpServletRequest request) {
		Map<String, Object> dataMap = new HashMap<>();

		String phoneCode = (String) request.getSession().getAttribute("phoneCode");
		String newPhone = (String) request.getSession().getAttribute("newPhone");
		// 手机校验
		Map<String, Object> checkMap = checkPhone(newPhone);
		if ((int) checkMap.get("code") != 0) {
			dataMap.put("code", 1);
			dataMap.put("message", checkMap.get("message"));
			return dataMap;
		}
		if (StringUtil.isEmpty(newPhone) || StringUtil.isEmpty(phoneCode)) {
			dataMap.put("code", 1);
			dataMap.put("message", MessageType.MT_SR_5);
			return dataMap;
		}
		// 验证码校验
		if (!verifyCode.equals(phoneCode)) {
			dataMap.put("code", 1);
			dataMap.put("message", MessageType.MT_YZ_1);
			return dataMap;
		}
		UserAuthsVO userAuthsVO = userAuthsMapper.selectByUserIdAndType(userId, "phone");
		// 业务处理
		try {
			UserVO userVO = userMapper.selectByPrimaryKey(userId);
			userVO.setMobile(newPhone);
			userMapper.updateByPrimaryKeySelective(userVO);
			userAuthsVO.setIdentifier(newPhone);
			userAuthsMapper.updateByPrimaryKeySelective(userAuthsVO);
			dataMap.put("code", 0);
		} catch (Exception e) {
			dataMap.put("code", 1);
			dataMap.put("message", MessageType.MT008);
			e.printStackTrace();
		}
		return dataMap;
	}

	public void delUserInfo(String phone) {
		
		UserVO userVO = userMapper.findUserByMobile(phone);
		userCardService.deleteUserCarByIdNo(userVO.getIdNum());
		userMapper.deleteUserByMobile(phone);
		verificationMapper.deleteByMobile(phone);
	}

	public UserVO findUserByMobile(String mobile) {
		
		return userMapper.findUserByMobile(mobile);
	}

	public void addUser(UserVO user) {
		user.setUserStatus(UserStatus.USER_NOMAL.getCode().byteValue());
		user.setCreateTime(new java.util.Date());
		userMapper.insert(user);
	}

	public UserVO findUserByCondition(Map<String, Object> map) {
		UserVO user = userMapper.selectUserByCondition(map);
		return user;
	}

	public UserVO findUserByNameOrPassword(String phone, String password) {
		Map<String, Object> accessMap = new HashMap<>();
		accessMap.put("mobile", phone);
		accessMap.put("password", password);
		UserVO user = userMapper.selectUserByNameOrPassword(accessMap);
		return user;
	}

	public void forgetPassword(String phone, String newPassword) {
		Map<String, Object> accessMap = new HashMap<>();
		accessMap.put("mobile", phone);
		accessMap.put("password", StringUtil.md5(newPassword));
		userMapper.updateUserByMobile(accessMap);
	}

	public void updateUserInfo(UserVO user) {
		userMapper.updateByPrimaryKeySelective(user);
	}

	public UserVO getUserByIdNo(String idNum) {
		return userMapper.selectUserByIdNo(idNum);
	}

	

}
